package com.jason.thread.sync;

/**
 * @description: 两个线程取钱案例
 * @author: jason.jia
 * @create: 2019-01-28 17:35
 **/
public class JAndCJob extends Thread{

    private BankAccount account = new BankAccount();

    public static void main(String[] args) {
        Runnable jAndc = new JAndCJob();
        Thread j = new Thread(jAndc);
        Thread c = new Thread(jAndc);
        j.setName("jason");
        c.setName("chris");
        j.start();
        c.start();
        System.out.println(j.getName() + j.getState());
        System.out.println(c.getName() + c.getState());
    }

    @Override
    public void run(){
        for (int i = 0; i < 10; i++) {
            makeWithdrawal(10);
            if (account.getBalance() < 0){
                System.out.println("透支了！");
            }
        }
    }

    private synchronized void makeWithdrawal(int amount) {
        System.out.println("============方法开始============");
        if(account.getBalance() >= amount){
            System.out.println(Thread.currentThread().getName() + " 想取钱");
            try {
                System.out.println(Thread.currentThread().getName() + " 正在睡觉");
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 醒了");
            account.withdraw(amount);
            System.out.println(Thread.currentThread().getName() + " 取完了钱，还剩" + account.getBalance());
        }else{
            System.out.println("对不起，" + Thread.currentThread().getName() + "，没钱了");
        }
        System.out.println("============方法结束============");
        System.out.println(Thread.currentThread().getState());
    }
}
